import 'package:distribution_mall_flutter/Introduction/Introduction_hone_one.dart';
import 'package:distribution_mall_flutter/Introduction/Introduction_product_banner.dart';
import 'package:distribution_mall_flutter/Introduction/Introduction_product_sample.dart';
import 'package:distribution_mall_flutter/base/base_service.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/point_constant.dart';
import 'package:distribution_mall_flutter/constant/status_constant.dart';
import 'package:distribution_mall_flutter/entity/address/address_entity.dart';
import 'package:distribution_mall_flutter/ext/toast_ext.dart';
import 'package:distribution_mall_flutter/http/modules/order.dart';
import 'package:distribution_mall_flutter/pages/address/address_create_edit/address_created_edit.dart';
import 'package:distribution_mall_flutter/pages/address/select_address/select_address_page.dart';
import 'package:distribution_mall_flutter/pages/goods/checkout/domain/checkout_pass_params.dart';
import 'package:distribution_mall_flutter/pages/goods/product_details/product_details_provider.dart';
import 'package:distribution_mall_flutter/pages/goods/checkout/modal_check.dart';
import 'package:distribution_mall_flutter/provider/goods/product_details.dart';
import 'package:distribution_mall_flutter/provider/order/order.dart';
import 'package:distribution_mall_flutter/provider/user/login.dart';
import 'package:distribution_mall_flutter/router/route_utils.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_analytics_utils.dart';
import 'package:distribution_mall_flutter/utils/navigator_utils.dart';
import 'package:distribution_mall_flutter/utils/overlay_manager.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'product_details_service.g.dart';

class ProductDetailsService extends BaseService {
  final String saleItemId;
  var sampleTextKey = GlobalKey();

  ProductDetailsService(super.ref, this.saleItemId);

  @override
  void onReady() {
    super.onReady();

    ///获取订单详情
    ref.read(pDetailProvider.notifier).setFirstLoading(true);
    ref.read(pDetailProvider.notifier).getDetail(saleItemId).catchError((e) {
      ref.read(pDetailProvider.notifier).setFirstLoading(false);
    }).whenComplete(() {
      ref.read(pDetailProvider.notifier).setFirstLoading(false);
      WidgetsBinding.instance.addPostFrameCallback((d) {
        ///如果没展示
        if (appRouter.current.name == ProductDetailsRoute.name &&
            EPstorage.guide
                .get(GuideBoxKey.productGuideGetBanner, defaultValue: true)) {
          showBannerGuide();
        } else {
          showSampleGuide();
        }
      });
    });

    ///初始化地址
    initAddress();
  }

  void showBannerGuide() {
    OverlayEntry? lastOverlay;
    lastOverlay = OverlayEntry(builder: (ctx) {
      return GestureDetector(
          onTap: () {
            ref.read(overlayManagerProvider.notifier).close(lastOverlay);
          },
          behavior: HitTestBehavior.opaque,
          child: const IntroductionProductBanner());
    });

    ref.read(overlayManagerProvider.notifier).insert(lastOverlay,
        closeListener: () {
      EPstorage.guide.put(GuideBoxKey.productGuideGetBanner, false);
      showSampleGuide();
    });
  }

  showSampleGuide() {
    ///并且这个是领样商品
    if (appRouter.current.name == ProductDetailsRoute.name &&
        ref.read(pDetailProvider).detail?.suInfo?.sample == true &&
        EPstorage.guide
            .get(GuideBoxKey.productGuideGetSample, defaultValue: true)) {
      OverlayEntry? lastOverlay;
      lastOverlay = OverlayEntry(builder: (ctx) {
        return GestureDetector(
            onTap: () {
              ref.read(overlayManagerProvider.notifier).close(lastOverlay);
            },
            behavior: HitTestBehavior.opaque,
            child: IntroductionProductSample(
              contentInfo: WidgetLocationInfo.fromKey(sampleTextKey)!,
            ));
      });
      ref.read(overlayManagerProvider.notifier).insert(lastOverlay,
          closeListener: () {
        EPstorage.guide.put(GuideBoxKey.productGuideGetSample, false);
      });
    }
  }

  Future<void> initAddress() async {
    if (EPstorage.isLogin()) {
      (await ref.read(userAddressProvider.notifier).initData())
          .yes((addressList) {
        ///设置默认地址
        if (addressList?.items?.isNotEmpty == true) {
          ///并且没设置过地址
          if (ref.read(userAddressProvider).userSelectAddress == null) {
            ref
                .read(userAddressProvider.notifier)
                .setAddressInfo(addressList!.items!.first);
          }
        }
      });
    }
  }

  Future<void> selectAddress(
      BuildContext context, List<AddressItem> addressList) async {
    if (ref.read(loginStateProvider)) {
      AddressItem? selectAddress;
      if (addressList.isNotEmpty) {
        DateTime startTime = DateTime.now();
        selectAddress = await showModalBottomSheet(
            context: context,
            enableDrag: false,
            isScrollControlled: true,
            builder: (_) => const EPModalAddressPage());
        RouteUtils.onStoreDialogStayTime(
          name: PointDialogNameConstant.pdAddressSelect,
          startTime: startTime,
          endTime: DateTime.now(),
        );
      } else {
        selectAddress = await appRouter
            .push(AddressCreateEditRoute(type: AddressActionType.add.name));
      }
      if (selectAddress != null) {
        ref.read(userAddressProvider.notifier).setAddressInfo(selectAddress);
      } else {
        ///判断现在地址里还包含已选择的地址.没有则移除
        if (!ref
            .read(userAddressProvider)
            .addressList
            .contains(selectAddress)) {
          ref.read(userAddressProvider.notifier).setAddressInfo(null);
        }
      }
    } else {
      appRouter.push(const LoginRoute());
    }
  }

  Future<void> getSample(BuildContext context) async {
    if (ref.read(loginStateProvider)) {
      int skuTotal =
          ref.read(pDetailProvider).sampleOrderItemList()?.length ?? 0;
      if (skuTotal > 0) {
        var sampleOrderItemGroupList =
            ref.read(pDetailProvider).sampleOrderItemGroupList;

        ///产品需求要在这里进行订单检查,由于没有service层,逻辑暂时写到这里
        Map<String, dynamic> map = {
          'orderType': OrderTypeConstant.sample,
        };
        if (ref.read(userAddressProvider).userSelectAddress != null) {
          map['consignee'] = Utils.formatConsignee(
              ref.read(userAddressProvider).userSelectAddress!.item);
        }

        map['isFirstTime'] = true;
        map['orderItemGroupList'] = {
          'transportType': ref
                      .read(pDetailProvider)
                      .detail
                      ?.suInfo
                      ?.shippingInfo
                      ?.isLocalShipping ==
                  true
              ? OrderTransportConstant.local
              : OrderTransportConstant.sea,
          'orderGoodsList': sampleOrderItemGroupList,
        };
        NavigatorUtils.showLoadingDialog(true);

        ///订单检查
        (await OrderApi.orderCheckout(map, showLoadingIndicator: true))
            .yes((onValue) {
          if (onValue == null) {
            return;
          }
          var sampleOrderItemList =
              ref.read(pDetailProvider).sampleOrderItemList()!;
          FirebaseAnalyticsUtils.logEvent(
              name: PointConstant.pdBuyClickSample,
              parameters: {
                'saleItemId':
                    sampleOrderItemList.map((e) => e.saleItemId).join(','),
                'spec': sampleOrderItemList
                    .map((e) => e.specInfos?[0].specValue ?? '')
                    .join(','),
              });
          EPModalBottomSheet.showCMBS(
              context: context,
              builder: (context) => ModalCheck(
                      checkoutPassParams: CheckoutPassParams(
                    orderType: OrderTypeConstant.sample,
                    skuTotal: skuTotal,
                    orderGoodsList: sampleOrderItemGroupList,
                    transportType: ref
                                .read(pDetailProvider)
                                .detail
                                ?.suInfo
                                ?.shippingInfo
                                ?.isLocalShipping ==
                            true
                        ? OrderTransportConstant.local
                        : OrderTransportConstant.sea,
                  )));
        });
      } else {
        'Sorry, the sample stock is insufficient.'.toast();
      }
    } else {
      appRouter.push(const LoginRoute());
    }
  }
}

@riverpod
ProductDetailsService productDetailsService(
    ProductDetailsServiceRef ref, String saleItemId) {
  return ProductDetailsService(ref, saleItemId);
}
